14. Hoisting

Hoisting

Sometimes your JavaScript code will produce errors that may seem counterintuitive at first. Hoisting is another one of those topics that might be the cause of some of these tricky errors you're debugging.

Let's take a look at an example:

Hoisting

Hoisting 1

What value will be printed to the console?

sayHi("Julia");

function sayHi(name) {
  console.log(greeting + " " + name);
  var greeting;
}
SOLUTION: undefined Julia

Hoisting 2

What value will be printed to the console?

sayHi("Julia");

function sayHi(name) {
  console.log(greeting + " " + name);
  var greeting = "Hello";
}
SOLUTION: undefined Julia

Hoisting 3

What value will be printed to the console?

function sayHi(name) {
  var greeting = "Hello";
  console.log(greeting + " " + name);
}

sayHi("Julia");
SOLUTION: Hello Julia